﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Otgruzka.ServicesClients;
using BusinessLogic.Statuses;
using BusinessLogic;
using BusinessLogic.Security;
using Otgruzka.Controls.jQuery;
using Common.Util;
using System.ServiceModel;
using DataTier.Entities;
using DataTier;

namespace Otgruzka.Controls.UserAccount
{
    public partial class CostsCenterEdit : System.Web.UI.UserControl
    {
        public int CostsCenterId
        {
            get 
            {
                int returned = 0;
                if ((!string.IsNullOrEmpty(this.hCostsCenterId.Value)))
                {
                    try
                    {
                        returned = Convert.ToInt32(this.hCostsCenterId.Value);
                    }
                    catch (Exception ex)
                    { }
                }
                return returned; 
            }
            set
            {
                this.hCostsCenterId.Value = value.ToString();
                BindData();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.ErrorMessage.Text = string.Empty;
            if (!IsPostBack)
            {
                BindDepartmentData();
                BindRolesData();
            }
        }


        /// <summary>
        /// Заполнение выпадающего списка Отделов
        /// </summary>
        void BindDepartmentData()
        {
            var client = new DictionariesClient();
            try
            {
                //департамент
                var depList = client.GetDepartmentList(UserPrincipal.Current.UserId);
                ddlDepartment.DataSource = depList;
                ddlDepartment.DataBind();
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
            }
        }


        /// <summary>
        /// Заполнение выпадающего списка Ролей
        /// </summary>
        void BindRolesData()
        {
            var client = new DictionariesClient();
            try
            {
                //Роли
                var roleList = client.GetRoleList(UserPrincipal.Current.UserId);
                ddlRoles.DataSource = roleList;
                ddlRoles.DataBind();
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
            }
        }


        /// <summary>
        /// Заполнение формы данными из базы
        /// </summary>
        void BindData()
        {
            ClearForm();
            var client = new DictionariesClient();
            try
            {
                var center = client.GetCostsCenterFullInfo(UserPrincipal.Current.UserId, CostsCenterId);
                if (center != null)
                {
                    // Заполнение формы данными
                    this.txtName.Text = center.Name;

                    //департамент
                    var depList = client.GetDepartmentList(UserPrincipal.Current.UserId);
                    ddlDepartment.DataSource = depList;
                    ddlDepartment.DataBind();
                    if (!string.IsNullOrEmpty(center.DepartmentName) && ddlDepartment.DataSource != null)
                        ddlDepartment.SelectedValue = center.DepartmentId.ToString();

                    //Роли
                    var roleList = client.GetRoleList(UserPrincipal.Current.UserId);
                    ddlRoles.DataSource = roleList;
                    ddlRoles.DataBind();
                    if (!string.IsNullOrEmpty(center.UserRole.Role.Name) && center.UserRole != null && center.UserRole.Role != null && ddlRoles.DataSource != null)
                        ddlRoles.SelectedValue = center.UserRole.Role.Id.ToString();

                    this.txtFIO.Text = center.UserFIO;
                    this.txtLogin.Text = center.UserLogin;
                    //this.txtPassword
                    this.txtEMail.Text = center.UserEmail;
                    this.txtPhone.Text = center.UserPhone;
                    this.cbxIsActive.Checked = center.UserIsEnable;
                }
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
            }
        }


        /// <summary>
        /// Очистка полей формы создания затрат
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnNewCostCenter_Click(object sender, EventArgs e)
        {
            CostsCenterId = 0;
        }

        private void ClearForm()
        {
            //департамент
            BindDepartmentData();
            //роль
            BindRolesData();

            // Очистка формы данными
            this.txtName.Text = "";
            this.txtFIO.Text = "";
            this.txtLogin.Text = "";
            this.txtPassword.Text = "";
            this.txtEMail.Text = "";
            this.txtPhone.Text = "";
            this.cbxIsActive.Checked = true;
        }

        /// <summary>
        /// Сохранение Центра затрат
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveCostCenter_Click(object sender, EventArgs e)
        {
            var center = GetCostsCenterFullInfoEntity();
            if (center != null)
            {
                var client = new DictionariesClient();
                try
                {
                    int id = client.SaveCostsCenterFullInfoEntity(UserPrincipal.Current.UserId, center);
                    CostsCenterId = id;
                }
                catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
                {
                    string message = client.GetExceptionDetail(ex);
                    this.ErrorMessage.Text = message;
                }
                catch (System.Exception exp)
                {
                    this.ErrorMessage.Text = exp.Message;
                }
            }
        }


        /// <summary>
        /// Создается объект Центр затра с информацией о пользователе и его правах на основании полей ввода формы
        /// </summary>
        /// <returns></returns>
        private CostsCenterFullInfoEntity GetCostsCenterFullInfoEntity()
        {
            var center = new CostsCenterFullInfoEntity()
            {
                CostsCenterId = CostsCenterId,
                Name = this.txtName.Text,

                //департамент
                DepartmentId = (this.ddlDepartment.SelectedItem != null) ? Convert.ToInt32(this.ddlDepartment.SelectedItem.Value) : (int?)null,
                DepartmentName = (this.ddlDepartment.SelectedItem != null) ? this.ddlDepartment.SelectedItem.Text : "",

                BS = this.txtLogin.Text,
                MVZ = this.txtPassword.Text,

                UserFIO = this.txtFIO.Text,
                UserLogin = this.txtLogin.Text,
                UserPassHash = (!string.IsNullOrEmpty(this.txtPassword.Text)) ? PasswordMD5Helper.GetMd5Hash(this.txtPassword.Text) : "",
                UserEmail = this.txtEMail.Text,
                UserPhone = this.txtPhone.Text,
                UserIsEnable = this.cbxIsActive.Checked,
                
                UserRole = new RoleEntity() 
                            { 
                                Role = new Role() 
                                        {
                                            Id = (this.ddlRoles.SelectedItem != null) ? Convert.ToInt32(this.ddlRoles.SelectedItem.Value) : 0,
                                            Name = (this.ddlRoles.SelectedItem != null) ? this.ddlRoles.SelectedItem.Text : ""
                                        }
                            }

            };

            return center;
        }
    }
}